﻿using System;
using System.Net;
using System.IO;

namespace CzfSDK
{
	public class CzfHttpListener
	{
		public event CzfEvent<HttpListenerContext> OnRequest;

		HttpListener listener;

		/// <summary>
		/// Initializes a new instance of the <see cref="CzfSDK.CzfHttpListener"/> class.
		/// </summary>
		/// <param name="urls">http://*:8099/</param>
		public CzfHttpListener (params string[] urls)
		{
			LogicTool.AssertNotNull (urls);
			LogicTool.Assert (urls.Length > 0);

			this.listener = new HttpListener();

			foreach (var url in urls) {
				listener.Prefixes.Add (url);
			}
		}

		public void Start()
		{
			listener.Start ();
			listener.BeginGetContext (GetContextCallBack, null);
		}

		void GetContextCallBack(IAsyncResult ar)
		{
			try{
				listener.BeginGetContext (GetContextCallBack, listener);
				var context = listener.EndGetContext (ar);
				if (OnRequest != null)
					OnRequest(context);
			}catch(Exception e){
				CzfLog.Error("GetContextCallBack", e);
			}
		}
	}
}

